#!/bin/bash

# 修复 Docker Compose 安装问题的脚本

set -e

# 颜色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"
}

error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
}

log "🔧 修复 Docker Compose 安装..."

# 1. 清理可能失败的 pip 安装
log "🧹 清理失败的安装..."
pip3 uninstall docker-compose -y 2>/dev/null || true

# 2. 使用二进制文件安装 Docker Compose
log "📦 下载 Docker Compose 二进制文件..."
DOCKER_COMPOSE_VERSION="2.20.0"

# 下载到临时目录
cd /tmp

# 尝试多个下载源（国内镜像优先）
log "尝试从国内镜像下载..."
curl -L "https://mirror.ghproxy.com/https://github.com/docker/compose/releases/download/v${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o docker-compose || \
curl -L "https://ghproxy.net/https://github.com/docker/compose/releases/download/v${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o docker-compose || \
curl -L "https://github.com/docker/compose/releases/download/v${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o docker-compose

# 检查下载是否成功
if [ -f docker-compose ] && [ -s docker-compose ]; then
    log "✅ 下载成功，安装 Docker Compose..."
    chmod +x docker-compose
    mv docker-compose /usr/local/bin/docker-compose
    ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
else
    error "❌ 下载失败，尝试备用方案..."
    # 备用方案：使用 Docker 插件
    log "📦 尝试安装 Docker Compose 插件..."
    dnf install -y docker-compose-plugin 2>/dev/null || {
        warn "无法安装 Docker Compose，但不影响主要功能"
        exit 0
    }
fi

# 3. 验证安装
log "🧪 验证 Docker Compose 安装..."
if command -v docker-compose &> /dev/null; then
    COMPOSE_VERSION=$(docker-compose --version)
    log "✅ Docker Compose 安装成功: $COMPOSE_VERSION"
elif docker compose version &> /dev/null; then
    COMPOSE_VERSION=$(docker compose version)
    log "✅ Docker Compose 插件安装成功: $COMPOSE_VERSION"
    # 创建别名
    echo 'alias docker-compose="docker compose"' >> /root/.bashrc
    log "✅ 已创建 docker-compose 别名"
else
    warn "❌ Docker Compose 安装失败，但不影响主要功能"
    log "💡 您仍然可以使用 docker build 和 docker run 命令"
fi

# 4. 继续安装其他组件
log "🐍 安装 Python 依赖..."
pip3 install flask

# 5. 创建项目目录
PROJECT_DIR="/opt/jpom/projects/tetris-game"
log "📁 确保项目目录存在..."
mkdir -p "${PROJECT_DIR}"
mkdir -p /var/log

# 6. 进入项目目录并创建必要文件
cd "${PROJECT_DIR}"

log "📝 创建项目配置文件..."

# 创建 Dockerfile
cat > Dockerfile << 'EOF'
# 多阶段构建 - 构建阶段
FROM node:18-alpine AS builder

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build

# 生产阶段
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
EOF

# 创建简化的构建脚本
cat > jpom-build.sh << 'EOF'
#!/bin/bash
set -e

PROJECT_NAME="tetris-game"
DOCKER_IMAGE_NAME="tetris-game"
DOCKER_CONTAINER_NAME="tetris-game"
DOCKER_PORT="3000"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

log "🚀 开始构建部署..."

# 拉取最新代码
if [ -d ".git" ]; then
    log "📥 拉取最新代码..."
    git pull origin main || git pull origin master
fi

# 停止旧容器
if docker ps -a --format 'table {{.Names}}' | grep -q "^${DOCKER_CONTAINER_NAME}$"; then
    log "🛑 停止旧容器..."
    docker stop "${DOCKER_CONTAINER_NAME}" || true
    docker rm "${DOCKER_CONTAINER_NAME}" || true
fi

# 删除旧镜像
if docker images --format 'table {{.Repository}}' | grep -q "^${DOCKER_IMAGE_NAME}$"; then
    log "🗑️ 删除旧镜像..."
    docker rmi "${DOCKER_IMAGE_NAME}" || true
fi

# 构建新镜像
log "🔨 构建 Docker 镜像..."
docker build -t "${DOCKER_IMAGE_NAME}:latest" .

# 启动新容器
log "🚀 启动新容器..."
docker run -d \
    --name "${DOCKER_CONTAINER_NAME}" \
    --restart unless-stopped \
    -p "${DOCKER_PORT}:80" \
    "${DOCKER_IMAGE_NAME}:latest"

# 等待容器启动
sleep 3

# 检查容器状态
if docker ps --format 'table {{.Names}}' | grep -q "^${DOCKER_CONTAINER_NAME}$"; then
    log "✅ 部署成功！"
    log "🌐 访问地址: http://82.157.51.127:${DOCKER_PORT}"
else
    log "❌ 容器启动失败，请检查日志: docker logs ${DOCKER_CONTAINER_NAME}"
    exit 1
fi
EOF

chmod +x jpom-build.sh

# 创建 Webhook 接收器
cat > webhook-receiver.py << 'EOF'
#!/usr/bin/env python3
import json
import subprocess
import os
from flask import Flask, request, jsonify
import logging
from datetime import datetime

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('/var/log/webhook-receiver.log'),
        logging.StreamHandler()
    ]
)

app = Flask(__name__)

BUILD_SCRIPT_PATH = "/opt/jpom/projects/tetris-game/jpom-build.sh"

@app.route('/webhook/gitee', methods=['POST'])
def gitee_webhook():
    try:
        data = request.get_json()
        logging.info(f"收到 Webhook: {data.get('hook_name', 'unknown')}")
        
        if data.get('hook_name') == 'push_hooks':
            logging.info("触发构建...")
            result = subprocess.run([BUILD_SCRIPT_PATH], capture_output=True, text=True, timeout=600)
            
            if result.returncode == 0:
                logging.info("构建成功")
                return jsonify({"message": "Build successful", "output": result.stdout}), 200
            else:
                logging.error(f"构建失败: {result.stderr}")
                return jsonify({"error": "Build failed", "output": result.stderr}), 500
        
        return jsonify({"message": "Not a push event"}), 200
    except Exception as e:
        logging.error(f"错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route('/health', methods=['GET'])
def health():
    return jsonify({
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "service": "webhook-receiver"
    }), 200

@app.route('/', methods=['GET'])
def index():
    return jsonify({
        "service": "Tetris Game Webhook Receiver",
        "version": "1.0.0",
        "endpoints": {
            "webhook": "/webhook/gitee",
            "health": "/health"
        }
    }), 200

if __name__ == '__main__':
    logging.info("Webhook 接收器启动中...")
    app.run(host='0.0.0.0', port=9999, debug=False)
EOF

chmod +x webhook-receiver.py

# 创建服务文件
cat > webhook-receiver.service << 'EOF'
[Unit]
Description=Tetris Game Webhook Receiver
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/jpom/projects/tetris-game
ExecStart=/usr/bin/python3 /opt/jpom/projects/tetris-game/webhook-receiver.py
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# 7. 配置并启动 Webhook 服务
log "⚙️ 配置 Webhook 服务..."
cp webhook-receiver.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable webhook-receiver
systemctl start webhook-receiver

# 8. 检查服务状态
log "📊 检查服务状态..."
sleep 2

echo ""
echo "=== 服务状态检查 ==="
systemctl is-active docker && echo "✅ Docker: 运行中" || echo "❌ Docker: 未运行"
systemctl is-active nginx && echo "✅ Nginx: 运行中" || echo "❌ Nginx: 未运行"
systemctl is-active webhook-receiver && echo "✅ Webhook: 运行中" || echo "❌ Webhook: 未运行"
systemctl is-active firewalld && echo "✅ 防火墙: 运行中" || echo "❌ 防火墙: 未运行"

echo ""
log "✅ 修复完成！"
echo ""
echo "🌐 访问地址:"
echo "  健康检查: http://82.157.51.127/health"
echo "  Webhook URL: http://82.157.51.127/webhook/gitee"
echo ""
echo "🔧 下一步操作:"
echo "1. 克隆您的项目代码到: ${PROJECT_DIR}"
echo "2. 执行构建测试: cd ${PROJECT_DIR} && ./jpom-build.sh"
echo "3. 在 Gitee 中配置 Webhook"
echo ""
echo "📝 查看日志:"
echo "  Webhook 日志: tail -f /var/log/webhook-receiver.log"
echo "  服务日志: journalctl -u webhook-receiver -f"
